package com.theydream.qeechain.collection;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.theydream.qeechain.R;
import com.theydream.qeechain.facebook.FacebookConnector;
import com.theydream.qeechain.facebook.SessionEvents;
import com.theydream.qeechain.globaldata.CaughtItemListClass;
import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.globaldata.definition.CaughtPet;

public class PetInfo extends Activity {
	private static final String FACEBOOK_APPID = "183524461720661";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	// private static final String TAG = "FacebookSample";
	private static final String MSG = "Message from FacebookSample";

	private final Handler mFacebookHandler = new Handler();
	private TextView loginStatus;
	private FacebookConnector facebookConnector;
	Location location;
	Button btnChangePet;
	TextView petAddress;
	Address mAddress=null;
	CaughtPet mPet;
	Bitmap bm;
	Drawable d;

	final Runnable mUpdateFacebookNotification = new Runnable() {
		public void run() {
			Toast.makeText(getBaseContext(), "Facebook updated !",
					Toast.LENGTH_LONG).show();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Bundle bundle = this.getIntent().getExtras();
		
		
			

		// ===========================================
		// | Show General Pet Info of with Facebook API
		// ===========================================
		if (!bundle.getBoolean("frombattle", false)) {
			setContentView(R.layout.pet_info);
			ImageView facebook = (ImageView) findViewById(R.id.facebook);
			this.facebookConnector = new FacebookConnector(FACEBOOK_APPID,
					this, getApplicationContext(),
					new String[] { FACEBOOK_PERMISSION });

		// ===========================================
		// | Get View By Id from xml
		// ===========================================
			
			// Set up the change pet button
			btnChangePet = (Button) findViewById(R.id.btn_mypet);
			btnChangePet.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					GlobalData.getInstance().getDbhelper()
							.setPetInUse(bundle.getInt("id"));
				}
			});
			facebook.setClickable(true);
			facebook.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					postMessage();
				}
			});
			
		// ===========================================
		// | SHow Pet Info After Battle
		// ===========================================
		} 
		else if ( bundle.getBoolean("frombattle", false) == true) 
		{
			setContentView(R.layout.pet_info_frombattle);
			//LoadPicTask picTask=new LoadPicTask();
			//picTask.execute(null);
		}
		
		
		ImageView petImage = (ImageView) findViewById(R.id.pet_image);
		TextView petName = (TextView) findViewById(R.id.pet_name);
		TextView petDesc = (TextView) findViewById(R.id.pet_desc);
		TextView petTime = (TextView) findViewById(R.id.caught_time);
		TextView petS = (TextView) findViewById(R.id.strength);
		TextView petP = (TextView) findViewById(R.id.perception);
		TextView petE = (TextView) findViewById(R.id.endurance);
		TextView petC = (TextView) findViewById(R.id.charisma);
		TextView petI = (TextView) findViewById(R.id.intelligence);
		TextView petA = (TextView) findViewById(R.id.agility);
		TextView petL = (TextView) findViewById(R.id.luck);
		petAddress = (TextView) findViewById(R.id.caught_address);
		
		// ===========================================
		// | Bind infomation to view
		// ===========================================
		if (bundle != null) {
			mPet = CaughtItemListClass.getInstance()
					.getItemList().get(bundle.getInt("id"));

			// get drawable resource by name
			petImage.setImageResource(getResources().getIdentifier(
					mPet.getPet().getPic(), "drawable",
					this.getPackageName()));

			GlobalData.getInstance().setCaughtPetImage(
					getResources().getIdentifier(mPet.getPet().getPic(),
							"drawable", this.getPackageName()));

			petName.setText(mPet.getPet().getName());
			petTime.setText(mPet.getTime());
			petDesc.setText(mPet.getPet().getDesc());

			Map<String, Integer> map = mPet.getPet().getAttr();
			petS.setText(map.get("S").toString());
			petP.setText(map.get("P").toString());
			petE.setText(map.get("E").toString());
			petC.setText(map.get("C").toString());
			petI.setText(map.get("I").toString());
			petA.setText(map.get("A").toString());
			petL.setText(map.get("L").toString());
			LoadAddressTask task=new LoadAddressTask();
			task.execute(null);


		}

	}
		
	

	public void postMessage() {

		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread();
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {

				@Override
				public void onAuthSucceed() {
					postMessageInThread();
				}

				@Override
				public void onAuthFail(String error) {

				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}

	private void postMessageInThread() {
		Thread t = new Thread() {
			public void run() {

				try {
					facebookConnector.postMessageOnWall(getFacebookMsg());
					mFacebookHandler.post(mUpdateFacebookNotification);

				} catch (Exception ex) {
				}
			}
		};
		t.start();
	}

	private String getFacebookMsg() {
		return MSG + " at " + new Date().toLocaleString();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.facebookConnector.getFacebook().authorizeCallback(requestCode,
				resultCode, data);
	}

	public void updateLoginStatus() {
		loginStatus.setText("Logged into Twitter : "
				+ facebookConnector.getFacebook().isSessionValid());
	}

	@Override
	protected void onResume() {
		super.onResume();
		// updateLoginStatus();
	}

	public void goBack(View target) {
		this.finish();
	}
	
	
	public class LoadAddressTask extends AsyncTask <Void, Void, Void>{
		ProgressDialog dialog;
		
		

		@Override
		protected void onPreExecute()
		{
//			dialog=new ProgressDialog(PetInfo.this);
//			dialog.setMessage("Loading...");
//			dialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// ===========================================
			// | Location to Address
			// ===========================================
			
			try {
				location = new Location("Caught Location");
				String lan=mPet.getLat();
				if (!lan.equals("NA"))	{
					location.setLatitude(Double.valueOf(mPet.getLat()));
					location.setLongitude(Double.valueOf(mPet.getLng()));
					double geoLatitude = location.getLatitude() * 1E6;
					double geoLongitude = location.getLongitude() * 1E6;
					GeoPoint gp = new GeoPoint((int) geoLatitude,
							(int) geoLongitude);
	
					Geocoder gc = new Geocoder(PetInfo.this, Locale.CHINA);
	
					double Latitude = (int) gp.getLatitudeE6() / 1E6;
					double Longitude = (int) gp.getLongitudeE6() / 1E6;
	
					List<Address> lstAddress;
					lstAddress = gc.getFromLocation(Latitude, Longitude, 1);
					if (lstAddress.size() > 0) {
						mAddress = lstAddress.get(0);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}
		protected void onPostExecute(Void result)
		{
			
			if (mAddress!=null)
			{
				petAddress.setText(mAddress.getAddressLine(1)
					.toString());
			}
		}
	}
	
	public class LoadPicTask extends AsyncTask <Void, Void, Void>{

		

		@Override
		protected void onPreExecute()
		{

		}
		@Override
		protected Void doInBackground(Void... params) {
			// ===========================================
			// |Load Image
			// ===========================================
			File sdImageMainDirectory = new File("/sdcard");
			 java.io.File file = new java.io.File(sdImageMainDirectory,
			 "/image.jpg");
			 if (file.exists()) 
			 {
			
				 try
				 {
					 BitmapFactory.Options options = new BitmapFactory.Options(); 
//						options.outHeight = h;
//						options.outWidth = w;
			            options.inSampleSize = 4;
						options.inInputShareable = true;
						options.inPurgeable = true;
						
					 bm = BitmapFactory.decodeFile(sdImageMainDirectory.toString() + "/image.jpg",options);
					 d = new BitmapDrawable(bm);
					 
				 }
				 catch (Exception e)
				 {}
			 }
			 
			return null;
			
		}
		protected void onPostExecute(Void result)
		{
			
			if (d!=null)
			{
				RelativeLayout rl = (RelativeLayout)findViewById(R.id.pet_info_frombattle);
				 rl.setBackgroundDrawable(d);
			}
		}
	}
	
	
}
